<?php
class AssignmentsController extends AppController {

	var $name = 'Assignments';
	
	
	function index($id) {
		$this->Assignment->recursive = 0;
		$this->paginate =  array(
							'conditions' => array('Assignment.project_id' => $id),
							'limit' => 20
							);
		$this->set('assignments', $this->paginate('Assignment'));
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid assignment', true));
			$this->redirect(array('action' => 'index'));
		}
		
		//print_r($_POST);
		
		$assignment_arr = $this->Assignment->read(null, $id);
		$count = $this->Assignment->find('count',array('conditions'=>array('Assignment.status'=>'locked','User.id'=>$this->Session->read('User.id'))));
		
		if ($count >= 3) {
			$this->Session->setFlash(__('You cannot lock more than 3 assignments at a time.', true));
			$this->redirect(array('controller' => 'projects','action' => 'index'));
		}
		
		if($this->Assignment->checkSubmissionTime($id)>0)
		{
			$this->Session->destroy();
			$this->Session->setFlash(__('You just got banned because you didn\'t submit the Assignment within allocated time.', true));			
			$this->redirect('/users/login');
		}

		if($this->Assignment->checkRevisionTime($id)>0)
		{
			$this->Session->write('User.status','flagged');
			$this->Session->setFlash(__('You just got flagged because you didn\'t submit the Revision within allocated time.', true));			
			$this->redirect('/projects/index');
		}
		
		if (isset($this->params['form']['status'])) {
			if ($assignment_arr['Assignment']['status'] == 'available') {
				//print_r($assignment_arr);
				//$this->Session->setFlash(__('Assignment not availabe!', true));
				$data['user_id'] = $this->Session->read('User.id');
				$data['status']  = $this->params['form']['status'];
				$data['datetime_started'] = DboSource::expression('NOW()');				
				$this->Assignment->save($data);				
				$this->Session->setFlash(__('Assignment locked successfully!', true));
				
				//print_r($this->Session->read('User.id'));
				
			} else {
				$this->Session->setFlash(__('Assignment not availabe for locking!', true));
			}
		}		
		
		
		if (isset($this->params['form']['code'])) {
			if (($assignment_arr['Assignment']['status'] == 'locked' || $assignment_arr['Assignment']['status'] == 'revision')
				&& $assignment_arr['Assignment']['user_id'] = $this->Session->read('User.id')) {
				
				$data['user_id']        = $this->Session->read('User.id');
				$data['assignment_id']  = $id;
				$data['submitted_time'] = DboSource::expression('NOW()');
				$data['code'] = $this->params['form']['code'];
				$this->Assignment->AssignmentCode->save($data);
				
				
				$data['status']           ='under_review';
				$data['datetime_stoped']  = DboSource::expression('NOW()');
				
				$this->Assignment->save($data);
				$this->redirect('/assignments/view/'.$id);
			}
		}
		
		if ($assignment_arr['Assignment']['status'] == 'revision' && count($assignment_arr['AssignmentCode'])) {
			//print_r($assignment_arr['AssignmentCode']);exit;
			$this->params['form']['code'] = $assignment_arr['AssignmentCode'][count($assignment_arr['AssignmentCode'])-1]['code'];
			
		}
		
		
		
		
		$assignment_arr = $this->Assignment->read(null, $id);
		
		$this->set('assignment', $assignment_arr);
	}

	function admin_index($id) {
		$this->Assignment->recursive = 0;
		$this->paginate =  array(
							'conditions' => array('Assignment.project_id' => $id),
							'limit' => 20
							);
		$this->set('assignments', $this->paginate('Assignment'));
		$this->set('assignment_id', $id);
	}
	
	function admin_review()
	{
		$this->Assignment->recursive = 0;
		$this->paginate =  array(
							'conditions' => array('Assignment.status' => 'under_review'),
							'limit' => 20
							);
		$this->set('assignments', $this->paginate('Assignment'));
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid assignment', true));
			$this->redirect(array('action' => 'index'));
		}
		$assignment_arr = $this->Assignment->read(null, $id);
		
		$code_arr = array();
		if ($assignment_arr['Assignment']['status'] == 'under_review') {
			
			//$conditions = array("AssignmentCode.user_id" => $assignment_arr['Assignment']['user_id']);	
			
			//$code_arr       = $this->Assignment->AssignmentCode->find('first', array('conditions' => $conditions));
		}
		
		if (isset($this->params['form']['status'])) {
			
			/* To add the amount to the user account */
			if( 'approved' == $this->params['form']['status'])
			{
				$total_amount = $assignment_arr['User']['total_amount'] + $assignment_arr['Assignment']['amount'];
				//$this->Assignment->User->save(array('total_amount' => $total_amount));			
				
				$db   = ConnectionManager::getInstance(); 
				$conn = $db->getDataSource('default'); 
				$sql  = "UPDATE `users` SET `total_amount` = '$total_amount' WHERE `id`='".$assignment_arr['User']['id']."'";
				$conn->rawQuery($sql); 
				
				/* $this->Assignment->User->save(
					,
					array('id' => $this->params['form']['user_id'])
				);
				*/
			}
			
			$data['status']           = $this->params['form']['status'];
			$data['datetime_started'] = DboSource::expression('NOW()');
			$data['datetime_stoped']  = '';
			$this->Assignment->save($data);
			$assignment_arr = $this->Assignment->read(null, $id);
			$this->Session->setFlash(__('Assignment updated successfully!', true));
		}
		
		$this->set('assignment', $assignment_arr);
		$this->set('code_arr', $code_arr);
		
	}

	function admin_add($id = null) {
		if (!empty($this->data)) {
			$this->Assignment->create();
			if ($this->Assignment->save($this->data)) {
				$this->Session->setFlash(__('The assignment has been saved', true));
				$this->redirect(array('action' => 'index/'.$this->data['Assignment']['project_id']));
			} else {
				$this->Session->setFlash(__('The assignment could not be saved. Please, try again.', true));
			}
		}
		$projects = $this->Assignment->Project->find('list');
		$users = $this->Assignment->User->find('list');
		$this->set(compact('projects', 'users'));
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid assignment', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Assignment->save($this->data)) {
				$this->Session->setFlash(__('The assignment has been saved', true));
				$this->redirect(array('action' => 'index/'.$this->data['Assignment']['project_id']));
			} else {
				$this->Session->setFlash(__('The assignment could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Assignment->read(null, $id);
		}
		$projects = $this->Assignment->Project->find('list');
		$users = $this->Assignment->User->find('list');
		$this->set(compact('projects', 'users'));
		$this->set('statuses', array('available'=>'Available', 'revision'=>'Revision', 'locked'=>'Locked', 'under_review'=>'Review', 'approved'=>'Approved'));
	}

	function admin_delete($id = null, $assignment_id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for assignment', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Assignment->delete($id)) {
			$this->Session->setFlash(__('Assignment deleted', true));
			$this->redirect(array('action'=>'index/'.$assignment_id));
		}
		$this->Session->setFlash(__('Assignment was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	/* For bulk upload */
	function admin_bulk_upload()
	{
		if(!empty($this->data))
		{
			$titles = explode("\n",$this->data['Assignment']['title']);
			$descriptions = explode("\n",$this->data['Assignment']['description']);			
			$amounts = explode("\n",$this->data['Assignment']['amount']);
			$temp = $this->data['Assignment']['project_id'];
			$this->data = array(); 
			$count=0;		//Count to take data from other arrays as well	
			$this->data['Assignment']['project_id'] = $temp;
			foreach($titles as $title)
			{				
				$this->data['Assignment']['title'] = $title;
				$this->data['Assignment']['description'] = $descriptions[$count*3];
				$this->data['Assignment']['amount'] = $amounts[$count];				
				$this->Assignment->create(); //save one item at a time
				$this->Assignment->save($this->data); //save one item at a time
				$count++; //as the description will have three breaks
			}			
			//$this->Session->setFlash(__('The Bulk assignments has been saved', true));
			//$this->redirect(array('action' => 'index/'.$this->data['Assignment']['project_id']));
		}
		$projects = $this->Assignment->Project->find('list');
		$users = $this->Assignment->User->find('list');
		$this->set(compact('projects', 'users'));
	}
}